#include "message.h"
#include <unistd.h>
#include "rf/event/RFEventManager.h"
#include "rf/event/rooftop_event.h"

namespace ProcessRouter {

static void listener_io_cb (EV_P_ ev_io *w, int revents)
{
    //printf("callback %s %d %d 0X%x %p\n", __FUNCTION__, w->fd, getpid(), revents, loop);
    std::list<Listener*> *listeners = (std::list<Listener*>*)ev_userdata(loop);
    std::list<Listener*>::iterator it = listeners->begin();
    for (; it != listeners->end(); it++) {
        if ((*it)) {
            if (w->fd == (*it)->fd()) {
                (*it)->onRecevied();
                break;
            }
        }
    }
}

Listener::Listener(IOThread *thread)
    : m_client(NULL)
    , m_currentThread(thread)
    , m_priority(0)
{
}

Listener::~Listener()
{
    if (m_client)
        delete m_client;
}

void Listener::init(int fd)
{
    m_fd = fd;
    ev_io_init(&m_watcher, listener_io_cb, m_fd, EV_READ);
}

void Listener::setClient(MessageProtocol *client)
{
    if (m_client)
        delete m_client;

    m_client = client;

    currentThread()->addListener((Listener*)this);
}

MessageProtocol* Listener::client()
{
    return m_client;
}

ev_io* Listener::watcher()
{
    return &m_watcher;
}

int Listener::fd()
{
    return m_fd;
}

void Listener::remove()
{
    currentThread()->removeListener((Listener*)this);
}

IOThread* Listener::currentThread()
{
    return m_currentThread;
}

void Listener::onRecevied()
{
    if (m_client)
        m_client->didRecevied();
}

void Listener::onConnected()
{
    if (m_client)
        m_client->didConnected();
}

void Listener::onError()
{
    if (m_client)
        m_client->didError();
}

void Listener::setPriority(int priority)
{
    m_priority = priority;
    ev_set_priority(&m_watcher, m_priority);
}

int Listener::priority()
{
    return m_priority;
}

}

